﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 软构大作业
{
    public partial class Form18 : Form
    {
        private new AutoAdaptWindowsSize AutoSize;
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        private int _bookId;
        private Data data = new Data();
        private string _imagesFolderPath = Path.Combine
            (Directory.GetParent
            (Directory.GetParent
            (Directory.GetParent
            (Directory.GetParent(Application.StartupPath).FullName).FullName).FullName).FullName, "book_picture"); // 图片文件夹路径

        // 添加属性来接收图书 ID
        public int BookId
        {
            get { return _bookId; }
            set
            {
                _bookId = value;
                LoadBookDetails(); // 加载图书详情
            }
        }
        public Form18()
        {
            InitializeComponent();
        }

        // 加载图书详情的方法
        private void LoadBookDetails()
        {
            try
            {
                string sql = "SELECT * FROM library_db.books WHERE book_id = @BookId";
                using (SqlConnection connection = new SqlConnection("Server=localhost;Database=library_2;Trusted_Connection=true"))
                {
                    connection.Open();
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        command.Parameters.AddWithValue("@BookId", _bookId);
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                textBox1.Text = reader["title"].ToString();
                                textBox2.Text = reader["author"].ToString();
                                textBox3.Text = reader["publisher"].ToString();
                                textBox4.Text = reader["category"].ToString();
                                textBox5.Text = reader["location"].ToString();
                                textBox6.Text = reader["description"].ToString();
                                textBox7.Text = reader["stock"].ToString();

                                // 加载图片 - 根据book_id从book_picture文件夹中获取
                                string imagePath = GetBookImagePath(_bookId);
                                if (!string.IsNullOrEmpty(imagePath) && File.Exists(imagePath))
                                {
                                    try
                                    {
                                        pictureBox1.Image = Image.FromFile(imagePath);
                                    }
                                    catch (Exception ex)
                                    {
                                        
                                        MessageBox.Show("加载图片时出错: " + ex.Message);
                                        pictureBox1.Image = null; // 清除图片框
                                    }
                                }
                                else
                                {
                                    pictureBox1.Image = null; // 如果没有图片，清除图片框
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载图书详情时出错: " + ex.Message);
            }
        }

        // 根据book_id获取图片路径
        private string GetBookImagePath(int bookId)
        {
            // 检查图片文件夹是否存在
            if (!Directory.Exists(_imagesFolderPath))
            {
                MessageBox.Show($"图片文件夹不存在: {_imagesFolderPath}");
                return null;
            }

            // 查找匹配的图片文件
            string[] imageFiles = Directory.GetFiles(_imagesFolderPath, $"{bookId}.*");

            // 支持常见图片格式
            string[] supportedExtensions = { ".jpg", ".jpeg", ".png", ".bmp", ".gif" };

            foreach (string ext in supportedExtensions)
            {
                string imagePath = Path.Combine(_imagesFolderPath, $"{bookId}{ext}");
                if (File.Exists(imagePath))
                {
                    return imagePath;
                }
            }

            // 如果没有找到完全匹配的文件名，尝试查找包含book_id的文件名
            foreach (string file in Directory.GetFiles(_imagesFolderPath))
            {
                string fileName = Path.GetFileNameWithoutExtension(file);
                if (fileName.Contains(bookId.ToString()))
                {
                    return file;
                }
            }

            return null;
        }

        private void Form18_Load(object sender, EventArgs e)
        {
            AutoSize = new AutoAdaptWindowsSize(this);
            this.SizeChanged += new EventHandler(Form_SizeChanged);
            // 可以在这里初始化图片文件夹路径
            // _imagesFolderPath = Path.Combine(Application.StartupPath, "book_picture");
        }

        //private void button1_Click(object sender, EventArgs e)
        //{
        //    // 确保用户已登录并且用户名有效
        //    if (Global.Instance.CurrentUser == null || string.IsNullOrEmpty(Global.Instance.CurrentUser.Username))
        //    {
        //        MessageBox.Show("用户未登录或用户信息无效，无法借阅。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //        return;
        //    }
        //    string currentUsername = Global.Instance.CurrentUser.Username; // 获取当前用户的用户名

        //    // 确保 _bookId 是有效的
        //    if (_bookId <= 0)
        //    {
        //        MessageBox.Show("未选择有效的图书。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //        return;
        //    }

        //    string connectionString = "Server=localhost;Database=library_3;Trusted_Connection=true";
        //    SqlConnection connection = null;
        //    SqlTransaction transaction = null;
        //    int currentUserId = 0; // 用于存储从数据库查询到的用户ID

        //    try
        //    {

        //        connection = new SqlConnection(connectionString);
        //        connection.Open();

        //        // --- 步骤 0: 根据 Username 获取 UserId ---
        //        string getUserIdSql = "SELECT user_id FROM library_db.users WHERE username = @Username"; // 假设用户表是 library_db.users
        //        using (SqlCommand getUserIdCommand = new SqlCommand(getUserIdSql, connection))
        //        {
        //            getUserIdCommand.Parameters.AddWithValue("@Username", currentUsername);
        //            object result = getUserIdCommand.ExecuteScalar(); // ExecuteScalar用于查询单个值

        //            if (result != null && result != DBNull.Value)
        //            {
        //                currentUserId = Convert.ToInt32(result);
        //            }
        //            else
        //            {
        //                MessageBox.Show($"无法找到用户 '{currentUsername}' 的ID，请检查用户信息。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //                return; // 获取不到UserId，则中止操作
        //            }
        //        }

        //        // 如果成功获取到UserId，则继续后续操作
        //        if (currentUserId <= 0) // 再次校验以防万一
        //        {
        //            MessageBox.Show("未能获取有效的用户ID。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //            return;
        //        }

        //        transaction = connection.BeginTransaction(); // 在获取到UserId后开始事务

        //        // --- 步骤 1: 更新图书库存 ---
        //        string updateStockSql = "UPDATE library_db.books SET stock = stock  WHERE book_id = @BookId AND stock > 0";
        //        int rowsAffectedStockUpdate;

        //        using (SqlCommand stockCommand = new SqlCommand(updateStockSql, connection, transaction))
        //        {
        //            stockCommand.Parameters.AddWithValue("@BookId", _bookId);
        //            rowsAffectedStockUpdate = stockCommand.ExecuteNonQuery();
        //        }

        //        if (rowsAffectedStockUpdate > 0)
        //        {
        //            // --- 步骤 2: 向 dbo.BorrowRecords 表插入新的借阅记录 ---
        //            string insertBorrowRecordSql = @"
        //        INSERT INTO dbo.BorrowRecords (user_id, book_id, borrow_time, return_time)
        //        VALUES (@UserId, @BookId, GETDATE(), NULL)";

        //            int rowsAffectedBorrowInsert;
        //            using (SqlCommand borrowCommand = new SqlCommand(insertBorrowRecordSql, connection, transaction))
        //            {
        //                borrowCommand.Parameters.AddWithValue("@UserId", currentUserId); // 使用查询到的currentUserId
        //                borrowCommand.Parameters.AddWithValue("@BookId", _bookId);
        //                rowsAffectedBorrowInsert = borrowCommand.ExecuteNonQuery();
        //            }

        //            if (rowsAffectedBorrowInsert > 0)
        //            {
        //                transaction.Commit();
        //                MessageBox.Show("借阅成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
        //                LoadBookDetails();
        //            }
        //            else
        //            {
        //                transaction.Rollback();
        //                MessageBox.Show("借阅失败：无法记录借阅信息。", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //            }
        //        }
        //        else
        //        {
        //            if (transaction != null) transaction.Rollback();
        //            MessageBox.Show("借阅失败：图书库存不足或图书不存在！", "失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //        }
        //    }
        //    catch (SqlException sqlEx)
        //    {
        //        if (transaction != null)
        //        {
        //            try { transaction.Rollback(); } catch { /* 回滚失败则忽略 */ }
        //        }
        //        MessageBox.Show("数据库操作出错: " + sqlEx.Message, "数据库错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //    }
        //    catch (Exception ex)
        //    {
        //        if (transaction != null)
        //        {
        //            try { transaction.Rollback(); } catch { /* 回滚失败则忽略 */ }
        //        }
        //        MessageBox.Show("借阅时发生未知错误: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //    }
        //    finally
        //    {
        //        if (connection != null && connection.State == ConnectionState.Open)
        //        {
        //            connection.Close();
        //        }
        //    }
        //}
        private void button1_Click(object sender, EventArgs e)
        {
            // 确保用户已登录并且用户名有效
            if (Global.Instance.CurrentUser == null || string.IsNullOrEmpty(Global.Instance.CurrentUser.Username))
            {
                MessageBox.Show("用户未登录或用户信息无效，无法借阅。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string currentUsername = Global.Instance.CurrentUser.Username; // 获取当前用户的用户名

            // 确保 _bookId 是有效的
            if (_bookId <= 0)
            {
                MessageBox.Show("未选择有效的图书。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string connectionString = "Server=localhost;Database=library_2;Trusted_Connection=true";
            SqlConnection connection = null;
            SqlTransaction transaction = null;
            int currentUserId = 0;
            bool userHasPermission = false; // 用于存储用户权限状态

            try
            {
                connection = new SqlConnection(connectionString);
                connection.Open();

                // --- 步骤 0: 根据 Username 获取 UserId 和 Permission ---
                // 同时查询 user_id 和 permission
                string getUserDetailsSql = "SELECT user_id, permission FROM library_db.users WHERE username = @Username";
                using (SqlCommand getUserDetailsCommand = new SqlCommand(getUserDetailsSql, connection))
                {
                    getUserDetailsCommand.Parameters.AddWithValue("@Username", currentUsername);
                    using (SqlDataReader reader = getUserDetailsCommand.ExecuteReader()) // 使用 ExecuteReader 因为要读取多列
                    {
                        if (reader.Read()) // 如果找到了用户记录
                        {
                            // 读取 user_id
                            if (reader["user_id"] != DBNull.Value)
                            {
                                currentUserId = Convert.ToInt32(reader["user_id"]);
                            }

                            // 读取 permission (假设 permission 在数据库中是 bit, bool, tinyint(1) 或 int 类型)
                            if (reader["permission"] != DBNull.Value)
                            {
                                // 根据数据库中 permission 的实际类型进行转换
                                // 如果是 bit 或 bool:
                                userHasPermission = Convert.ToBoolean(reader["permission"]);
                                // 如果是 int (0 或 1):
                                // userHasPermission = (Convert.ToInt32(reader["permission"]) == 1);
                            }
                        }
                        else
                        {
                            MessageBox.Show($"无法找到用户 '{currentUsername}' 的信息，请检查用户信息。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return; // 找不到用户记录，中止操作
                        }
                    } // SqlDataReader 会在此处 Dispose
                }

                // 再次校验获取到的 UserId
                if (currentUserId <= 0)
                {
                    MessageBox.Show("未能获取有效的用户ID。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // --- 步骤 0.5: 检查借阅权限 ---
                if (!userHasPermission)
                {
                    MessageBox.Show("抱歉，您当前没有借阅权限，无法借阅图书。\n请联系管理员申请权限。", "权限不足", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return; // 没有权限，中止操作
                }

                // --- 后续操作（事务、更新库存、插入借阅记录）---
                transaction = connection.BeginTransaction(); // 在权限检查通过后开始事务

                // --- 步骤 1: 更新图书库存 ---
                // !!! 重要：修复库存更新SQL语句 !!!
                string updateStockSql = "UPDATE library_db.books SET stock = stock WHERE book_id = @BookId AND stock > 0";
                int rowsAffectedStockUpdate;
                
                using (SqlCommand stockCommand = new SqlCommand(updateStockSql, connection, transaction))
                {
                    stockCommand.Parameters.AddWithValue("@BookId", _bookId);
                    rowsAffectedStockUpdate = stockCommand.ExecuteNonQuery();
                }

                if (rowsAffectedStockUpdate > 0)
                {
                    // --- 步骤 2: 向 dbo.BorrowRecords 表插入新的借阅记录 ---
                    string insertBorrowRecordSql = @"
        INSERT INTO dbo.BorrowRecords (user_id, book_id, borrow_time, return_time)
        VALUES (@UserId, @BookId, GETDATE(), NULL)";

                    int rowsAffectedBorrowInsert;
                    using (SqlCommand borrowCommand = new SqlCommand(insertBorrowRecordSql, connection, transaction))
                    {
                        borrowCommand.Parameters.AddWithValue("@UserId", currentUserId);
                        borrowCommand.Parameters.AddWithValue("@BookId", _bookId);
                        rowsAffectedBorrowInsert = borrowCommand.ExecuteNonQuery();
                    }

                    if (rowsAffectedBorrowInsert > 0)
                    {
                        transaction.Commit();
                        MessageBox.Show("借阅成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadBookDetails();
                    }
                    else
                    {
                        transaction.Rollback();
                        MessageBox.Show("借阅失败：无法记录借阅信息。", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    if (transaction != null) transaction.Rollback();
                    MessageBox.Show("借阅失败：图书库存不足或图书不存在！", "失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (SqlException sqlEx)
            {
                if (transaction != null)
                {
                    try { transaction.Rollback(); } catch { /* 回滚失败则忽略 */ }
                }
                MessageBox.Show("数据库操作出错: " + sqlEx.Message, "数据库错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                if (transaction != null)
                {
                    try { transaction.Rollback(); } catch { /* 回滚失败则忽略 */ }
                }
                MessageBox.Show("借阅时发生未知错误: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (connection != null && connection.State == ConnectionState.Open)
                {
                    connection.Close();
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form_SizeChanged(object sender, EventArgs e)
        {//窗体大小改变事件
            if (AutoSize != null) // 一定加这个判断，电脑缩放布局不是100%的时候，会报错
            {
                AutoSize.FormSizeChanged();
            }
        }
    }
}